package com.allwayz.controller;

import com.allwayz.entity.CommonResult;
import com.allwayz.entity.Payment;
import com.allwayz.service.PaymentService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author allwayz
 */
@RestController()
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 读取到application.yml中配置的端口号
     */
    @Value("${server.port}")
    private String serverPort;

    @PostMapping()
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        if(result > 0){
            return new CommonResult(200,"Create Success",result);
        }else {
            return new CommonResult(500,"Create Fail",null);
        }
    }

    @GetMapping("/{id}")
    public CommonResult getPaymentById(@PathVariable Long id){
        Payment payment = paymentService.getPaymentById(id);
        if(payment != null){
            return new CommonResult(200,"查询成功: "+serverPort,payment);
        }else {
            return new CommonResult(404,"无对应记录",null);
        }
    }

    @GetMapping()
    public CommonResult getPaymentList(){
        List<Payment> paymentList = paymentService.getPaymentList();
        if (paymentList.size() != 0){
            return new CommonResult(200,"查询成功: "+serverPort,paymentList);
        }else {
            return new CommonResult(404,"无数据",null);
        }
    }

    @GetMapping("discovery")
    public Object discovery(){
        List<String> stringList = discoveryClient.getServices();
        for(String string:stringList){
            log.info("server: " + string);
        }
        log.info("==============================================");
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for(ServiceInstance serviceInstance:serviceInstanceList){
            log.info(serviceInstance.getServiceId()+"\t"+serviceInstance.getHost()+"\t"+serviceInstance.getPort()+"\t"+serviceInstance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("lb")
    public String getPaymentLoadBalancer(){
        return serverPort;
    }

    @GetMapping("timeout")
    public String paymentFeignTimeout(){
        try{
            TimeUnit.SECONDS.sleep(3);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("zipkin")
    public String paymentZipkin(){
        return "This is Payment Zipkin...";
    }
}
